package com.fengxu.netty.tcp.protocol;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;


public class MyClient {

    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(bossGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new MyMessageEncoder());
                        ch.pipeline().addLast(new MyMessageDecoder());
                        ch.pipeline().addLast(new MyClientHandler());
                    }
                });
        bootstrap.connect("127.0.0.1",6666).sync()
                .channel().closeFuture().sync();
    }

    // 自定义handler处理器
    private static class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            for (int i = 0; i < 8; i++) {
                String msg = "你好啊,世界!";
                byte[] bytes = msg.getBytes("utf-8");
                int len = bytes.length;
                MessageProtocol protocol = new MessageProtocol();
                protocol.setLen(len).setContent(bytes);
                ctx.writeAndFlush(protocol);
            }
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
            System.out.println("收到服务器返回消息:"+msg);
        }
    }
}

